package com.cszy.ewmxns.base

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cysd.ewmxns.base.IViewModel
import com.cysd.ewmxns.base.SingleLiveEvent


import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

open class BaseViewModel : ViewModel(), IViewModel, DefaultLifecycleObserver {

    val ui: UIChange by lazy { UIChange() }

    /**
     * 网络请求在viewModelScope域中启动，页面销毁时会调用onCleared方法取消所有协程
     */
    fun launch(block: suspend CoroutineScope.() -> Unit) = viewModelScope.launch() { block() }

    /**
     * UI事件
     */
    inner class UIChange {
        val showDialog by lazy { SingleLiveEvent<String>() }
        val dismissDialog by lazy { SingleLiveEvent<Void>() }
        val toast by lazy { SingleLiveEvent<String>() }
        val msgEvent by lazy { SingleLiveEvent<BaseEvent>() }
    }

    override fun showLoading(text: String) {
        ui.showDialog.postValue(text)
    }

    override fun dismissLoading() {
        ui.dismissDialog.call()
    }

    override fun toast(text: String) {
        ui.toast.postValue(text)
    }

    override fun handleEvent(event: BaseEvent) {
        ui.msgEvent.postValue(event)
    }

}